# @Time : 2023/1/6
# @Author : SDAJAVA
import urllib.request
from lxml import etree


# url = "https://sc.chinaz.com/tupian/fengjingtupian.html"
#
# https://sc.chinaz.com/tupian/fengjingtupian_2.html

def create_request(page):
    if (page == 1):
        url = 'https://sc.chinaz.com/tupian/fengjingtupian.html'
    else:
        url = 'https://sc.chinaz.com/tupian/fengjingtupian_' + str(page) + '.html'

    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
    }

    request = urllib.request.Request(url=url, headers=headers)
    return request


def get_content(request):
    response = urllib.request.urlopen(request)
    content = response.read().decode('utf-8')
    return content


def down_load(content):
    tree = etree.HTML(content)
    # 这里有个小问题需要注意就是F12查看class="tupian-list com-img-txt-list masonry" 实际返回的content是class="tupian-list com-img-txt-list"需要注意一下
    name_list = tree.xpath('//div[@class="tupian-list com-img-txt-list"]//img/@alt')
    src_list = tree.xpath('//div[@class="tupian-list com-img-txt-list"]//img/@data-original')
    for i in range(len(name_list)):
        name = name_list[i]
        src = src_list[i]
        img_url = "https:" + src
        # 不可以创建文件夹，需要先创建文件夹
        urllib.request.urlretrieve(url=img_url, filename="./fengjing/" + name + ".jpg")


if __name__ == '__main__':
    start_page = int(input('输入起始页:'))
    end_page = int(input('输入结束页:'))

    for page in range(start_page, end_page + 1):
        request = create_request(page)
        content = get_content(request)
        down_load(content)
